#include "add_student.h"
#include "ui_add_student.h"
#include <QCloseEvent>
#include <QMessageBox>
#include <QSqlQuery>
add_Student::add_Student(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::add_Student)
{
    ui->setupUi(this);
    connect2db();
}

add_Student::~add_Student()
{
    delete ui;
}

void add_Student::connect2db()
{
    //通过不同数据库的驱动程序连接不同的数据库
    db = QSqlDatabase::addDatabase("QSQLITE");     //添加SQLite3
    //设置SQLite数据库文件的名称
    db.setDatabaseName("student_info.db");
    //设置连接的用户名密码
    db.setUserName("admin");
    db.setPassword("admin");
    //打开数据库链接
    if(db.open())
    {
        qDebug() << "数据库连接成功!";
    }
    else
    {
        QSqlError error = db.lastError();
        //获得错误信息
        QString text = error.text();
        //展示错误信息
        QMessageBox::critical(this,"错误",text);
    }
}

void add_Student::createtable()
{

}

void add_Student::insertRow()
{
        QString name = ui->lineEdit->text();
        if(name == "")
        {
             QMessageBox::warning(this,"提示","请输入姓名");
             return;
        }
        int id = ui->spinBox->value();
        QString subject = ui->comboBox->currentText();
        QString score = ui->lineEdit_2->text();

    //拼接有可能会导致SQL注入问题
    //    QString sql = "INSERT INTO student values(" +QString::number(id)+ ",\" + name+ "\',\'"
    //    +subject+

        //所以使用预处理会更加安全
        QString sql = "INSERT INTO student VALUES(?,?,?,?)";
        QSqlQuery sq;
        //先对SQL语句进行预处理
        sq.prepare(sql);

        //添加参数
        sq.addBindValue(id);
        sq.addBindValue(name);
        sq.addBindValue(subject);
        sq.addBindValue(score);

        if(sq.exec())
        {
            QMessageBox::information(this,"通知","添加成功!");
            close();
        }
        else
        {
            QString text = sq.lastError().text();
            QMessageBox::warning(this,"警告",text);
        }

}

void add_Student::closeEvent(QCloseEvent *)
{
    emit add_close();
}

void add_Student::on_pushButton_2_clicked()
{
    close();
}

void add_Student::on_pushButton_clicked()
{
    insertRow();
}
